package cn.tx.api.controller;

import cn.tx.api.config.WebSocket;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * Websocket 测试
 * @author cuixinfu
 * @date 2022-04-26 10:28
 */
@RestController
@RequestMapping("/api/webSocket")
public class WebSocketController {
    // 测试地址：https://blog.csdn.net/weixin_43757027/article/details/124454843
    @Resource
    private WebSocket webSocket;

    @GetMapping("/index")
    public String index(){
        return "index";
    }

    /**
     * 发送消息
     * @param userId
     * @param message
     */
    @PostMapping("/sentMessage")
    public void sentMessage(String userId,String message){
        try {
            webSocket.sendMessageByUserId(userId,message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @GetMapping("/test")
    @ResponseBody
    public String sendMessage(String msg){
        //如果访问的地址中msg参数不为空值，发送msg的值给前端
        if(!StringUtils.isEmpty(msg)){
            webSocket.sendMessage(msg);
            return "服务端发送消息msg："+msg;
        }
        return "服务端未发送消息msg："+msg;
    }

}

